package com.ruoyi.web.controller.monitor;

import com.google.gson.Gson;
import com.ruoyi.system.domain.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ClassName PlatformAsyncWebSocket * @Description TODO
 * @Author ZQB
 * @Date 21:33 2024/2/18
 * @Version 1.0
 **/
@Component
@Slf4j
// 类似于controlelr 服务点
@ServerEndpoint(value = "/websocket/{userId}")
public class PlatformAsyncWebSocket {

    // 用来存储每一个客户端对象对应的WsController对象
    private static CopyOnWriteArraySet<PlatformAsyncWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    //当前在线连接数
    private static int onlineCount = 0;
    // 声明Session对象，通过该对象可以给指定的用户发送请求
    private Session session;

    //接收sid
    private String userId = "";

    /**
     * 连接建立时被调用
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        log.info("连接成功");
        // 将局部的session对象赋值给成员session对象
        this.session = session;
        // 这里是因为前端在传数据的时候，会将userId传过来
        //所以使用将userId和websocket对象存储起来，方便下次服务端推送信息的时候使用
        this.userId = userId;
        addOnlineCount();
        webSocketSet.add(this);

        try {
            sendMessage("conn_success");
            log.info("有新窗口开始监听:" + userId + ",当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("websocket IO Exception");
        }

    }

    /**
     * 接收到客户端消息时被调用
     */
    @OnMessage
    public void onMessage(String message) {
        // 创建 Gson 对象
        Gson gson = new Gson();

        // 将 JSON 字符串转换为对象
//        MyObject obj = gson.fromJson(jsonString, MyObject.class);
        log.info("收到来自窗口" + userId + "的信息:" + message);

        sendInfo("11335", message);
    }

    /**
     * 连接被关闭时调用
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1

        log.info("释放的sid为："+userId);

        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());


    }


    //推送消息
    //将消息推送给某个指定的用户
    public void sendInfo(@PathParam("userId") String userId, String message) {

        for (PlatformAsyncWebSocket item : webSocketSet) {
            try {
                //为null则全部推送
                if (userId == null) {
//                    item.sendMessage(message);
                } else if (item.userId.equals(userId)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                log.error("用户{} 发送信息{}失败", userId, message);
                e.printStackTrace();
            }
        }



    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        PlatformAsyncWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        PlatformAsyncWebSocket.onlineCount--;
    }

    public static CopyOnWriteArraySet<PlatformAsyncWebSocket> getWebSocketSet() {
        return webSocketSet;
    }




}

